
from DBWrapper import DBWrapper
from threading import Thread
import logging
    
class Consumer(Thread):
    
    def __init__(self, dbconn, contracts, queue): 
        super(Consumer, self).__init__()
        self.dbconn     = DBWrapper(dbconn)
        self.contracts  = contracts        
        self.queue      = queue
        self.stopflag   = False
        self.running    = False
                
         
    def stop(self):
        logging.getLogger().debug("Stopping consumer thread")
        self.stopflag = True
        with self.queue.mutex:
            self.queue.queue.clear()
            
    def run(self):        
        logging.getLogger().debug("Starting consumer thread")
        self.running = True
        while self.stopflag == False:
            obj = self.queue.get()
            if (obj != None):
                logging.getLogger().debug("Consumed : %s" % obj)
                self.dbconn.add(obj)        
        self.running = False        
                 
    def __del__(self):
        if self.running:           
            self.stop()
    